package ivan.cheng.activitys;

import ivan.cheng.Const;
import ivan.cheng.R;
import ivan.cheng.adapter.PermissionExplainListAdapters.PermissionExplainListAdapter;
import ivan.cheng.utils.LogUtil;
import ivan.cheng.utils.Util;
import ivan.cheng.views.MyListView;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

public class AppDetailActivity extends UIActivity implements OnClickListener{

	private PermissionExplainListAdapter adapter;
	private PackageManager mPackageManager;
	private BroadcastReceiver loadFinish = new LoadFinishReceiver();
	private ArrayList<String> normalLst = new ArrayList<String>();
	private ArrayList<String> dangerousLst = new ArrayList<String>();
	private ArrayList<String> systemLst = new ArrayList<String>();
	private ArrayList<String> deepSystemLst = new ArrayList<String>();
	private String mPackageName;
	private MyListView listView;
	// private View mHeaderView;
	private int mSelecTab = 1;// 默认选中敏感权限权限
	private int privateIndex = 0;//隐私泄露指数
	private boolean isAllowedInternet = false;
	private RatingBar mRatingBar;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.list_app_detail);
		mTitle = (TextView) findViewById(R.id.custom_title_txt);
		mTitle.setText(R.string.permission_detail);
		listView = (MyListView) this.findViewById(R.id.listbody);
		mPackageManager = this.getApplicationContext().getPackageManager();
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		mPackageName = bundle.getString(Const.EXTRA_PACKAGE_NAME);
		IntentFilter filter = new IntentFilter(
				Const.ACTION_APP_DETAIL_LOADFINISH);
		this.registerReceiver(loadFinish, filter);
		((Button)findViewById(R.id.check_button)).setOnClickListener(this);
		findViewById(R.id.tab_normal_permission).setOnClickListener(this);
		findViewById(R.id.tab_dangerous_permission).setOnClickListener(this);
		findViewById(R.id.tab_system_permission).setOnClickListener(this);
		findViewById(R.id.tab_deep_system_permission).setOnClickListener(this);
		mRatingBar = (RatingBar) findViewById(R.id.ratingbar); 
		// 获取数据刷新列表
		refresh();
		SetViewHeader();
	}

	/**
	 * 显示系统设置应用程序详细界面
	 * 
	 * @param packageName
	 */
	public void showInstalledAppDetails(String packageName) {
		Intent intent = new Intent();
		final int apiLevel = Build.VERSION.SDK_INT;
		if (apiLevel >= 9) { // 2.3（ApiLevel 9）以上，使用SDK提供的接口
			intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
			Uri uri = Uri.fromParts("package", packageName, null);
			intent.setData(uri);
		} else { // 2.3以下，使用非公开的接口
			// 2.2和2.1中，InstalledAppDetails使用的APP_PKG_NAME不同。
			final String appPkgName = (apiLevel == 8 ? "pkg"
					: "com.android.settings.ApplicationPkgName");
			intent.setAction(Intent.ACTION_VIEW);
			intent.setClassName("com.android.settings",
					"com.android.settings.InstalledAppDetails");
			intent.putExtra(appPkgName, packageName);
		}
		startActivity(intent);
	}

	private MyListView getListView() {
		return listView;
	}

	public void refresh() {
		setProgressBarIndeterminateVisibility(true);
		normalLst.clear();
		dangerousLst.clear();
		systemLst.clear();
		deepSystemLst.clear();
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				PackageInfo perLst;
				try {
					perLst = mPackageManager.getPackageInfo(mPackageName,
							PackageManager.GET_PERMISSIONS);

					if (null == perLst.requestedPermissions)
						return;
					for (String name : perLst.requestedPermissions) 
					{
						PeekPermissionExplain(name);
					}
				} catch (NameNotFoundException e) {
					e.printStackTrace();
				}
				Intent in = new Intent(Const.ACTION_APP_DETAIL_LOADFINISH);
				AppDetailActivity.this.sendBroadcast(in);
			}

		});
		t.start();
	}

	protected void SetViewHeader() {
		// mHeaderView =
		// LayoutInflater.from(AppDetailActivity.this).inflate(R.layout.list_detail_item,
		// null);
		try {
			PackageInfo dp = mPackageManager.getPackageInfo(mPackageName,
					PackageManager.GET_PERMISSIONS);
			((ImageView) findViewById(R.id.list_icon))
					.setImageDrawable(dp.applicationInfo
							.loadIcon(mPackageManager));
			((TextView) findViewById(R.id.list_name))
					.setText(dp.applicationInfo.loadLabel(mPackageManager)
							.toString());
			if (null == dp.requestedPermissions)
				((TextView) findViewById(R.id.permission_count))
						.setText(AppDetailActivity.this.getResources()
								.getString(R.string.permission_count, 0));
			else {
				int w = Util.GetWarningPermissionCount(dp, mPackageManager);
				((TextView) findViewById(R.id.permission_count)).setText(Html
						.fromHtml(AppDetailActivity.this.getResources()
								.getString(R.string.permission_count,
										dp.requestedPermissions.length)
								+ "<br><font size=\"5\" color=\"0xee0000\">"
								+ AppDetailActivity.this.getResources()
										.getString(R.string.dangdrous_count, w)
								+ "</font>"));
			}
		} catch (NameNotFoundException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void PeekPermissionExplain(String sPermission) 
	{
		//这里添加安全指数检查
		if(sPermission.equalsIgnoreCase("android.permission.INTERNET"))
		{
			isAllowedInternet = true;
		}
		else if(sPermission.equalsIgnoreCase("android.permission.RECEIVE_SMS"))
		{
			privateIndex += 1;
		}else if(sPermission.equalsIgnoreCase("android.permission.READ_SMS"))
		{
			privateIndex += 3;
		}else if(sPermission.equalsIgnoreCase("android.permission.PROCESS_OUTGOING_CALLS"))
		{
			privateIndex += 2;
		}else if(sPermission.equalsIgnoreCase("android.permission.READ_CONTACTS"))
		{
			privateIndex += 4;
		}else if(sPermission.equalsIgnoreCase("android.permission.RECEIVE_MMS"))
		{
			privateIndex += 1;
		}else if(sPermission.equalsIgnoreCase("android.permission.ACCESS_COARSE_LOCATION"))
		{
			privateIndex += 1;
		}else if(sPermission.equalsIgnoreCase("android.permission.ACCESS_FINE_LOCATION"))
		{
			privateIndex += 1;
		}else if(sPermission.equalsIgnoreCase("android.permission.GET_ACCOUNTS"))
		{
			privateIndex += 1;
		}else if(sPermission.equalsIgnoreCase("android.permission.READ_CALENDAR"))
		{
			privateIndex += 1;
		}
		PermissionInfo tmpPermInfo = null;
		StringBuilder sb = new StringBuilder();
		try {
			tmpPermInfo = mPackageManager.getPermissionInfo(sPermission, 0);// 通过permName得到该权限的详细信息
			PermissionGroupInfo pgi = mPackageManager.getPermissionGroupInfo(
					tmpPermInfo.group, 0);// 权限分为不同的群组，通过权限名，我们得到该权限属于什么类型的权限。
			sb.append("<b><font size=\"5\" color=\"0x3acbff\">权限类别</font></b>")
					.append("-" + pgi.loadLabel(mPackageManager).toString()
							+ "<br>");
		} catch (NameNotFoundException e) {
			LogUtil.w("Could'nt retrieve permissions for package");
		}
		if (null != tmpPermInfo) {
			sb.append("<b><font size=\"5\" color=\"0x3acbff\">权限描述</font></b>")
					.append("-"
							+ tmpPermInfo.loadLabel(mPackageManager).toString()
							+ "<br>");
			if (null != tmpPermInfo.loadDescription(mPackageManager)) {
				sb.append(
						"<b><font size=\"5\" color=\"0x3acbff\">权限详情</font></b>")
						.append("-"
								+ tmpPermInfo.loadDescription(mPackageManager)
										.toString());
			}

			switch (tmpPermInfo.protectionLevel) {
			case PermissionInfo.PROTECTION_NORMAL:
				normalLst.add(sb.toString());
				break;
			case PermissionInfo.PROTECTION_DANGEROUS:
				dangerousLst.add(sb.toString());
				break;
			case PermissionInfo.PROTECTION_SIGNATURE:
				systemLst.add(sb.toString());
				break;
			case PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM:
				deepSystemLst.add(sb.toString());
				break;
			default:
				break;
			}
		}
		else
		{
//			this.runOnUiThread(new Runnable() {
//				
//				@Override
//				public void run() {
//					Toast.makeText(AppDetailActivity.this, getString(R.string.permission_get_failure), Toast.LENGTH_SHORT).show();
//				}
//			});
//			
//			finish();
		}
	}

	private class LoadFinishReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(final Context ctx, Intent intent) {
			AppDetailActivity.this.setProgressBarIndeterminateVisibility(false);
			RefreshTab();
			if(true == isAllowedInternet)
				mRatingBar.setRating(((float)privateIndex)/3);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(loadFinish);
	}

	public void RefreshTab() 
	{
		
		if (null == adapter) {
			adapter = new PermissionExplainListAdapter(AppDetailActivity.this,
					dangerousLst);
			AppDetailActivity.this.getListView().setAdapter(adapter);
		} 
		else 
		{
			findViewById(R.id.tab_normal_permission).setBackgroundColor(getResources().getColor(R.color.black));
			((TextView)findViewById(R.id.tab_normal_permission)).setTextColor(getResources().getColor(R.color.grey));
			findViewById(R.id.tab_dangerous_permission).setBackgroundColor(getResources().getColor(R.color.black));
			((TextView)findViewById(R.id.tab_dangerous_permission)).setTextColor(getResources().getColor(R.color.grey));
			findViewById(R.id.tab_system_permission).setBackgroundColor(getResources().getColor(R.color.black));
			((TextView)findViewById(R.id.tab_system_permission)).setTextColor(getResources().getColor(R.color.grey));
			findViewById(R.id.tab_deep_system_permission).setBackgroundColor(getResources().getColor(R.color.black));
			((TextView)findViewById(R.id.tab_deep_system_permission)).setTextColor(getResources().getColor(R.color.grey));
			if (0 == mSelecTab)
			{
				findViewById(R.id.tab_normal_permission).setBackgroundColor(getResources().getColor(R.color.sky_blue));
				((TextView)findViewById(R.id.tab_normal_permission)).setTextColor(getResources().getColor(R.color.white));
				adapter.SetData(normalLst);
			}
			else if (1 == mSelecTab)
			{
				findViewById(R.id.tab_dangerous_permission).setBackgroundColor(getResources().getColor(R.color.sky_blue));
				((TextView)findViewById(R.id.tab_dangerous_permission)).setTextColor(getResources().getColor(R.color.white));
				adapter.SetData(dangerousLst);
			}
				
			else if (2 == mSelecTab)
			{
				findViewById(R.id.tab_system_permission).setBackgroundColor(getResources().getColor(R.color.sky_blue));
				((TextView)findViewById(R.id.tab_system_permission)).setTextColor(getResources().getColor(R.color.white));
				adapter.SetData(systemLst);
			}
			else if (3 == mSelecTab)
			{
				findViewById(R.id.tab_deep_system_permission).setBackgroundColor(getResources().getColor(R.color.sky_blue));
				((TextView)findViewById(R.id.tab_deep_system_permission)).setTextColor(getResources().getColor(R.color.white));
				adapter.SetData(deepSystemLst);
			}
			else
				LogUtil.w("So wield thing~~ @ appDetailActivity");
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void PackageAdded(String packageName) {
		if (mPackageName.equalsIgnoreCase(packageName)) {

		}
	}

	@Override
	public void PackageRemoved(String packageName) {
		if (mPackageName.equalsIgnoreCase(packageName)) {

		}
	}

	@Override
	public void onClick(View v) 
	{
		switch (v.getId()) 
		{
		case R.id.tab_normal_permission:
			mSelecTab = 0;
			RefreshTab();
			break;
		case R.id.tab_dangerous_permission:
			mSelecTab = 1;
			RefreshTab();
			break;
		case R.id.tab_system_permission:
			mSelecTab = 2;
			RefreshTab();
			break;
		case R.id.tab_deep_system_permission:
			mSelecTab = 3;
			RefreshTab();
			break;
		case R.id.check_button:
			showInstalledAppDetails(mPackageName);
			break;
		default:
			break;
		}
	}

}
